//
//  ComposeViewController.swift
//  我的微博
//
//  Created by 贾永强 on 15/10/14.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD

//微博文字最大长度
private let statusTextMaxLength = 10

class ComposeViewController: UIViewController, UITextViewDelegate {
    
    
    //键盘输入视图,默认键盘高度216
    private lazy var emoticonVC: EmoticonViewController = EmoticonViewController { [weak self] (emoticon) -> () in
        
        self?.textView.insertEmoticon(emoticon)
        
    }
    // MARK: - 按钮方法
    /// 关闭
    func close() {
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 发布微博
    func sendStatus() {
        let text = textView.text
        // 1. 检查文字长度
        if text.characters.count > statusTextMaxLength {
            SVProgressHUD.showInfoWithStatus("输入的内容太长", maskType: SVProgressHUDMaskType.Gradient)
            return
        }
        
        // 2. 发布微博
        NetworkTools.sharedTools.postStatus(text) { (result, error) -> () in
            if error != nil {
                SVProgressHUD.showInfoWithStatus("网络不给力，请稍候再试", maskType: SVProgressHUDMaskType.Gradient)
                return
            }
            self.close()
        }
    }
    
    /// 选择表情
    func inputEmoticon() {
        //1,关闭键盘
        textView.resignFirstResponder()
        
        //2.设置输入键盘
        textView.inputView = (textView.inputView == nil) ? emoticonVC.view : nil
        
        //3.激活键盘
        textView.becomeFirstResponder()
        
    }
    
    // MARK: - UITextViewDelegate
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        placeHolderLabel.hidden = textView.hasText()
        
        let len = statusTextMaxLength - textView.text.characters.count
        textLengthLabel.text = String(len)
        textLengthLabel.textColor = len < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
    }
    
    // MARK: - 键盘处理
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /// 工具栏底部约束
    var toolbarBottomCons: NSLayoutConstraint?
    
    /// 键盘变化监听方法，是由通知中心监听到之后，由运行循环来调度执行，不能设置成 private 的
    func keyboardChanged(n: NSNotification) {
        
        // 动画的时间选项
        // `7` 的功能
        // 1> 如果连续两个动画，会执行后面的动画，前面的动画会直接停止
        // 2> 使用此选项，动画的时长就是 0.5s，动画时长属性无效
        let curve = n.userInfo![UIKeyboardAnimationCurveUserInfoKey]!.integerValue
        
        // 获取目标 frame
        let rect = n.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        // 动画时长
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        // 设置约束
        toolbarBottomCons?.constant = -UIScreen.mainScreen().bounds.height + rect.origin.y
        
        // 动画
//                UIView.animateWithDuration(duration) {
//                    self.view.layoutIfNeeded()
//                }
//     
        UIView.animateWithDuration(duration) {
            // 设置动画的时间选项为7  键盘切换表情的时候 就不会跳动
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            
            self.view.layoutIfNeeded()
        }
        
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        textView.becomeFirstResponder()
    }
    
    // MARK: - 搭建界面
    override func loadView() {
        view = UIView()
        view.backgroundColor = UIColor.whiteColor()
        
        prepareNav()
        prepareToolBar()
        prepareTextView()
    }
    
    /// 准备文本视图
    private func prepareTextView() {
        view.addSubview(textView)
        
        textView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolbar, size: nil)
        
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
        
        view.addSubview(textLengthLabel)
        textLengthLabel.ff_AlignInner(type: ff_AlignType.BottomRight, referView: textView, size: nil, offset: CGPoint(x: -8, y: -8))
    }
    
    /// 准备工具栏
    private func prepareToolBar() {
        
        // 1. 添加工具栏
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        view.addSubview(toolbar)
        
        let cons = toolbar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        toolbarBottomCons = toolbar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        // 2. 准备按钮数组
        let itemSettings = [["imageName": "compose_toolbar_picture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        // 3. 遍历按钮数组添加按钮
        var items = [UIBarButtonItem]()
        for item in itemSettings {
            // 添加按钮
            items.append(UIBarButtonItem(imageName: item["imageName"]!, target: self, actionName: item["action"]))
            
            // 添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        
        toolbar.items = items
    }
    
    /// 准备导航栏
    private func prepareNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
        
        let titleLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 15)
        titleLabel.text = "发微博"
        titleLabel.sizeToFit()
        titleView.addSubview(titleLabel)
        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        
        let nameLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 13)
        nameLabel.text = UserAccount.sharedAccount?.name ?? ""
        nameLabel.sizeToFit()
        titleView.addSubview(nameLabel)
        nameLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        navigationItem.titleView = titleView
    }
    
    // MARK: 懒加载控件
    /// 工具栏
    private lazy var toolbar: UIToolbar = UIToolbar()
    /// 文本视图
    private lazy var textView: UITextView = {
        let tv = UITextView()
        
        tv.font = UIFont.systemFontOfSize(18)
        tv.alwaysBounceVertical = true
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        tv.delegate = self
        
        return tv
        }()
    /// 占位标签
    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel(color: UIColor.lightGrayColor(), fontSize: 18)
        
        label.text = "分享新鲜事..."
        label.sizeToFit()
        
        return label
        }()
    /// 长度提示标签
    private lazy var textLengthLabel: UILabel = UILabel(color: UIColor.redColor(), fontSize: 12)
}
